package com.sc.byahi.user.client;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import com.google.gwt.core.client.GWT;
import com.google.gwt.dom.client.SpanElement;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.uibinder.client.UiHandler;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.PopupPanel;
import com.google.gwt.user.client.ui.TextArea;
import com.google.gwt.user.client.ui.Widget;

public class EmailView extends Composite {

	private static EmailViewUiBinder uiBinder = GWT.create(EmailViewUiBinder.class);

	interface EmailViewUiBinder extends UiBinder<Widget, EmailView> {
	}

	@UiField
	SpanElement to;
	@UiField
	SpanElement error;
	@UiField
	TextArea body;
	@UiField
	Button send;
	@UiField
	Button cancel;

	private Long toId;

	public EmailView(Long toId) {
		this.toId = toId;
		initWidget(uiBinder.createAndBindUi(this));
		to.setInnerHTML(toId.toString());
		error.setClassName("approved");
	}

	@UiHandler("send")
	void onClick(final ClickEvent e) {
		if (validate().isEmpty()) {
			String message = body.getText().trim();
			if (message.length() > 300) {
				message = message.substring(0, 299);
			}

			GreetingService.Util.getInstance().sendMessage(AppController.get().getCurrentProfileId(), toId, message, new AsyncCallback<Boolean>() {
				@Override
				public void onSuccess(Boolean result) {
					// PopupPanel popup = (PopupPanel) (ft.getParent().getParent());
					PopupPanel popup = (PopupPanel) (send.getParent().getParent().getParent());
					popup.hide();
					UIUtil.showDialog(Arrays.asList("Your email sent to profile id: "+toId + " is waiting to be approved."), "Email sending sucess.");
				}

				@Override
				public void onFailure(Throwable caught) {
					UIUtil.showDialog(Arrays.asList("Some error occured in sending email. Please try again.", "If the error persists, please contact administrator."), "Email sending failed.");
				}
			});
		}

	}

	@UiHandler("cancel")
	void onClick1(final ClickEvent e) {
//		PopupPanel popup = (PopupPanel) (((Button) e.getSource()).getParent().getParent());
		PopupPanel popup = (PopupPanel) this.getParent();
		popup.hide();

	}

	private List<String> validate() {
		body.removeStyleName("invalidEntry");
		error.setClassName("approved");
		error.setInnerHTML("");
		List<String> errors = new ArrayList<String>();

		String bodyText = body.getText().trim();
		if ("".equals(bodyText)) {
			body.addStyleName("invalidEntry");
			errors.add("Message text is empty.");
		}

		if (!errors.isEmpty()) {
			error.setClassName("unapproved");
			error.setInnerHTML("Please write your message.");
		}

		return errors;
	}
}
